package com.mrjy.maintain.bo;

import com.mrjy.common.dto.UserParaDto;
import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.SMSSendInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserPwd;
import com.mrjy.common.util.*;
import com.mrjy.integral.dao.IIntegralInfoDao;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.dao.ISMSSendInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserPwdDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userPwdBo")
public class UserPwdBo implements IUserPwdBo {

	@Resource
	private IUserPwdDao userPwdDao;
	@Resource
	private IUserInfoDao userInfoDao;
	@Resource
	private ISMSSendInfoDao smsSendInfoDao;
    @Resource
    private IIntegralInfoDao integralInfoDao;

    @Override
    public String txSafeValidateEmail(UserParaDto userParaDto) {
		UserInfo userInfo = new UserInfo();
		if ("email".equals(userParaDto.getMethod())) {
			userInfo.setLoginCode(userParaDto.getLoginCode());
			userInfo.setEmail(userParaDto.getEmail());
			UserInfo existUser = userInfoDao.queryBySafeValidate(userInfo);
			if (existUser == null) {
				return "misMatch";
			} else {
				String encode = RandomUtil.generateString(11) + new Date().getTime()+"_"+existUser.getId();
				String email = existUser.getEmail();
                String loginCode = existUser.getUserName() != null ? existUser.getUserName() : existUser.getMobilePhone();

                UserPwd userPwd = new UserPwd();
				userPwd.setUserId(existUser.getId());
				userPwd.setEncode(encode);
				userPwd.setIp(userParaDto.getIp());
				userPwd.setExpire(DateUtil.longToString(new  Date().getTime()+3600000, DateUtil.FULL_DATE));
				userPwd.setDisableFlag(0);
				userPwd.setMethod("email");
				userPwdDao.insert(userPwd);
				sendMail(email,encode,loginCode);
				return "ok";
			}
		}else {
			return "error";
		}
	}

	@Override
	public Object phoneValidate(String mobilePhone) {
		UserInfo userInfo = new UserInfo();
		userInfo.setMobilePhone(mobilePhone);
		UserInfo existUser = userInfoDao.queryBySafeValidate(userInfo);
		if (existUser != null) {
			return "ok";
		}else {
			return "phoneError";
		}
	}

	@Override
	public String safeValidatePhone(UserParaDto userParaDto) {
		UserInfo userInfo = new UserInfo();
		userInfo.setLoginCode(userParaDto.getLoginCode());
		userInfo.setMobilePhone(userParaDto.getMobilePhone());
		UserInfo existUser = userInfoDao.queryBySafeValidate(userInfo);
		UserPwd userPwd = new UserPwd();
		userPwd.setUserId(existUser.getId());
		String encode = RandomUtil.generateString(11) + new Date().getTime()
				+ "_" + existUser.getId();
		userPwd.setEncode(encode);
		userPwd.setIp(userParaDto.getIp());
		userPwd.setExpire(DateUtil.longToString(new Date().getTime() + 3600000,
				DateUtil.FULL_DATE));
		userPwd.setDisableFlag(0);
		userPwd.setMethod("phone");
		userPwdDao.insert(userPwd);
		return "ok&" + encode;
			
	}
	
	//发送邮件
	private void sendMail(String email,String encode,String loginCode){
        Mail mail = new Mail();
        mail.setHost("smtp.exmail.qq.com"); // 设置邮件服务器
        mail.setSender("mrjtjy@mrjtjy.com");
        mail.setReceiver(email); // 接收人
        mail.setUsername("mrjtjy@mrjtjy.com"); // 登录账号,一般都是和邮箱名一样
        mail.setPassword("1993Ying0319..."); // 发件人邮箱的登录密码
        mail.setSubject("明人教育科技：密码重置");
	     mail.setMessage(loginCode+"您好！请点击或者复制该链接到浏览器打开链接对您的账号进行邮箱验证（有效时间为1个小时）"
	     		+ "<a target='_blank' href='http://zhongguojiazhang.cn:83/update_pwd.html?mark="+encode+"'>http://zhongguojiazhang.cn:83/update_pwd.html?mark="+encode+"</a>"); 
	     new MailUtil().send(mail); 
	}

	@Override
	public String expireValidate(UserPwd userPwd) {
		UserPwd u = userPwdDao.queryByMark(userPwd);
		if (u == null) {
			return "error";
		} else {
			String date = DateUtil.longToString(new  Date().getTime(), DateUtil.FULL_DATE);
			if (date.compareTo(u.getExpire()) <= 0) {
				return "ok";
			} else {
				return "error";	
			}
		}
	}

	@Override
	public String txChangePassword(UserPwd userPwd) {
		UserPwd u = userPwdDao.queryByMark(userPwd);
		if (u == null) {
			return "error";
		} else {
//			return "ok";
//			Integer userId = Integer.valueOf(userPwd.getEncode().split("_")[1]);
			UserInfo userInfo = userInfoDao.queryById(u.getUserId());
			if (userInfo == null) {
				return "error";
			}
			userInfo.setPassword(MD5Encrypt.encryptByMD5(userPwd.getPassword()));
			userInfoDao.updateById(userInfo);
			u.setDisableFlag(1);
			userPwdDao.updateById(u);
			return "ok";
		}
	}

	@Override
	public Object txRetPwd(String mobilePhone, String validCode, String newPwd,
			String confirmPwd,Integer typeId) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo info = userInfoDao.queryByMobilePhone(mobilePhone);
		if (null != info) {
			SMSSendInfo smsSendInfo=new SMSSendInfo();
			smsSendInfo.setRecNum(mobilePhone);
			smsSendInfo.setSendCode(validCode);		
			smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(typeId));
//			smsSendInfo.setSmsCode("SMS_16440022");
			SMSSendInfo smsSendInfoDB=smsSendInfoDao.validateSMSCode(smsSendInfo);
			if (smsSendInfoDB == null) {
				map.put("err_code", 2);
				map.put("err_msg", "验证码错误");
			} else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date().getTime()) {
				map.put("err_code", 3);
				map.put("err_msg", "验证码失效");
			}else {
				if (newPwd.equals(confirmPwd)) {
                    //新增需求 修改密码得积分（只能得一次积分）
                    IntegralInfo paramInfo = new IntegralInfo();
                    paramInfo.setUserId(info.getId());
                    paramInfo.setInfoId(info.getId());
                    //根据用户id和类型id查询其有没有记录
                    paramInfo.setTypeId(IntegralEnum.MODIFY_PASSWORD.getTypeId());
                    List<IntegralInfo> list = integralInfoDao.queryListByInfo(paramInfo);
                    if (list == null || list.size() == 0) {
                        IntegralInfo integral = IntegralUtil.setIntegral(info.getId()
                                , IntegralEnum.MODIFY_PASSWORD.getScore()
                                , IntegralEnum.MODIFY_PASSWORD.getTypeDesc()
                                , IntegralEnum.MODIFY_PASSWORD.getTypeId()
                                , info.getId());


                        map.put("score", integral.getScore());
                    }

					info.setPassword(MD5Encrypt.encryptByMD5(newPwd));
					int count = userInfoDao.updateById(info);
					if (count > 0) {
						map.put("err_code", 0);
						map.put("err_msg", "密码重置成功");
					}else {
						map.put("err_code", 5);
						map.put("err_msg", "密码重置失败");
					}
				}else {
					map.put("err_code", 4);
					map.put("err_msg", "新密码与确认密码不相同");
				}
			}
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "该手机号还没注册");
		}
		return map;
	}
}
